﻿using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using Foundation;
using Foundation.ExtensionMethods;
using Poet.Properties;

namespace Poet.ViewModels
{
    [DataContract]
    internal class RecentFileManagerViewModel : ViewModel
    {
        public RecentFileManagerViewModel()
        {
            Initialize();
        }

        /// <summary>
        /// Gets the recent documents.
        /// </summary>
        [DataMember]
        public ObservableCollection<RecentFileViewModel> RecentFiles { get; private set; }

        public RecentFileViewModel Add(string fileName)
        {
            if (string.IsNullOrEmpty(fileName)) return null;

            var recentViewModel = RecentFiles.FirstOrDefault(vm => vm.Path == fileName);
            if (recentViewModel != null)
            {
                var oldIndex = RecentFiles.IndexOf(recentViewModel);
                RecentFiles.Move(oldIndex, 0);
            }
            else
            {
                recentViewModel = new RecentFileViewModel {Path = fileName};
                RecentFiles.Insert(0, recentViewModel);
            }

            //RecentFiles.Truncate(Settings.Default.RecentDocumentsCount);
            //Clear();
            return recentViewModel;
        }

        public void Remove(RecentFileViewModel item)
        {
            if (File.Exists(item.SerializeFileName))
                File.Delete(item.SerializeFileName);
            RecentFiles.Remove(item);
        }

        public void Clear(bool? pinned = null)
        {
            if (pinned == true) RecentFiles.Where(i => i.IsPinned).ToArray().ForEach(Remove);
            if (pinned == false) RecentFiles.Where(i => !i.IsPinned).ToArray().ForEach(Remove);
            if (pinned == null) RecentFiles.ToArray().ForEach(Remove);
        }

        [OnDeserialized]
        private void Initialize(StreamingContext context = default(StreamingContext))
        {
            RecentFiles = RecentFiles ?? new ObservableCollection<RecentFileViewModel>();
            RecentFiles.CollectionChanged += (sender, args) => this.SerializeDataContractAsync();
            ApplicationClosing += () => this.SerializeDataContractAsync();
        }
    }
}
